<template>
  <span ref="textContainer"></span>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';

const props = defineProps({
  text: {
    type: String,
    required: true
  },
  speed: {
    type: Number,
    default: 50 // 打字速度（毫秒/字符）
  },
  delay: {
    type: Number,
    default: 0 // 开始打字前的延迟（毫秒）
  }
});

const textContainer = ref(null);
let currentText = '';
let currentIndex = 0;
let timeoutId = null;

const typeText = () => {
  if (currentIndex < props.text.length) {
    currentText += props.text[currentIndex];
    if (textContainer.value) {
      textContainer.value.textContent = currentText;
    }
    currentIndex++;
    timeoutId = setTimeout(typeText, props.speed);
  }
};

const startTyping = () => {
  currentText = '';
  currentIndex = 0;
  if (timeoutId) {
    clearTimeout(timeoutId);
  }
  if (props.delay > 0) {
    timeoutId = setTimeout(typeText, props.delay);
  } else {
    typeText();
  }
};

watch(() => props.text, () => {
  startTyping();
});

onMounted(() => {
  startTyping();
});

// 组件销毁时清理定时器
onUnmounted(() => {
  if (timeoutId) {
    clearTimeout(timeoutId);
  }
});
</script> 